package structure;

import java.util.Iterator;
import java.util.Vector;

import listener.ListChangeEvent;
import listener.ListChangeListener;
import model.Participant;
import view.Launch;

public class ParticipantVector extends Vector<Participant> implements Runnable {
	private static final long serialVersionUID = -3299219593523051243L;
	private final static int ME_WAIT_LONG_TIME = 100;

	private int previous;
	private Thread thread;
	private Vector<ListChangeListener> listeners;
	
	public ParticipantVector() {
		previous = 0;
		listeners = new Vector<ListChangeListener>();
		
		thread = new Thread(this);
		thread.start();
	}
	
	private void createEvent() {
		ListChangeEvent e = new ListChangeEvent(this);
		Iterator<ListChangeListener> i = listeners.iterator();
		while (i.hasNext())
			i.next().listChanged(e);
	}
	
	public void addListChangeListener(ListChangeListener e) {
		if (listeners.contains(e))
			return;
		listeners.add(e);
	}
	
	public void removeListChangeListener(ListChangeListener e) {
		if (!listeners.contains(e))
			return;
		listeners.remove(e);
	}
	
	private boolean increased = true;
	public boolean hasIncreased() {
		return increased;
	}

	public void run() {
		while (true) {
			if (previous != size()) {
				increased = previous > size();
				previous = size();
				createEvent();
			} try {
				Thread.sleep(ME_WAIT_LONG_TIME);
			} catch (InterruptedException e) {
				if (Launch.DEBUG) e.printStackTrace();
			}
		}
	}
}
